import pika
#核心是，RPC服务器在收到请求时执行，完成工作并将响应发回
credentials = pika.PlainCredentials('chenjing', '253455')
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='192.168.31.80',port=5672, virtual_host='/', credentials=credentials))

channel = connection.channel()

channel.queue_declare(queue='rpc_queue')#声明队列
#声明斐波那契函数，它只假设有效的正整数输入，用最简单的递归实现
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)

def on_request(ch, method, props, body):
    #收到消息
    n = int(body)
    print(" [.] fib(%s)" % n)
    #要处理的任务
    response = fib(n)
#发布消息，通知到客户端
    ch.basic_publish(exchange='',
                     routing_key=props.reply_to,
                     properties=pika.BasicProperties(correlation_id = \
                                                         props.correlation_id),
                     body=str(response))
    #手动响应
    ch.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)

print(" [x] Awaiting RPC requests")
channel.start_consuming()